package com.hc.page.controller;

import com.hc.common.entity.Products;
import com.hc.page.feign.ProductsFeign;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;
@RefreshScope   //手动刷新获取Config配置中心微服务中的最新数据 触发刷新:POST请求http://localhost:10000/actuator/refresh
@RestController
@RequestMapping("page")
public class PageController {

    //1）RestTemplate由SpringMVC提供,用于实现Controller间的调用
    /*
    * 存在问题
    * 1.url地址写在代码中，不方便后期维护
    * 2.相同的服务形成集群后，无法实现负载均衡
    * 3.消费端不清楚服务端状态，异常无法良好的处理
    * 4.相同的配置代码信息冗余(数据库连接)
    */
    //默认未初始化 需要在启动类手动配置
//    @Autowired
//    private RestTemplate restTemplate;

    //2）DiscoveryClient注册中心的客户端 用于获取注册中心的数据
//    @Autowired
//    private DiscoveryClient discoveryClient;

    @Autowired
    private ProductsFeign productsFeign;

//    @Value("${mysql.user}")
    private String user;

    @Value("${config.username}")
    private String username;

    @Value("${config.age}")
    private Integer age;

    @Value("${config.sex}")
    private String sex;

    @RequestMapping("select/{id}")
    public Products selectById(@PathVariable Integer id){
//        String url = "http://localhost:9000/products/select/" + id;//1）
        //获取注册中心的服务提供方实例
//        List<ServiceInstance> instanceList = discoveryClient.getInstances("service-product");//2）服务应用名称是什么，这里字符串就是什么
//        ServiceInstance serviceInstance = instanceList.get(0);
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();
//        System.out.println("获取到服务提供方信息-----host:" + host + " ,port: " + port);
//        String url = "http://" + host + ":" + port + "/products/select/" + id;//1）
//        getMetaData(instanceList); //获取eureka自定义数据
//        return restTemplate.getForObject(url,Products.class);//1）
        return productsFeign.selectById(id);
    }

//    @HystrixCommand(
//        threadPoolKey = "selectPort",
//        threadPoolProperties = {
//            @HystrixProperty(name = "coreSize",value = "2"),
//            @HystrixProperty(name = "maxQueueSize",value = "20")
//                                },
//        commandProperties = {
//            //时间窗口：统计请求结果的过程
//            //活动窗口：熔断后至自动恢复过程
//            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "2000"), //请求超时时间
//            @HystrixProperty(name = "metrics,rollingStats,timeInMilliseconds",value = "8000"), //时间窗口整体时长
//            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "50"), //时间窗口请求失败率
//            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "2"), //时间窗口内最小请求数
//            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "5000") //活动窗口整体时长
//                            },
//        fallbackMethod = "failCallback"  //服务方响应异常时调用目标方法,并将该方法返回值给客户端
//    ) //如果服务提供方长时间未响应,则服务消费方通过Hystrix来控制服务的调用
    @RequestMapping("selectPort")
    public String selectPort(){
//        String url = "http://service-product/products/selectPort";
//        return restTemplate.getForObject(url,String.class);
        return productsFeign.selectPort();
    }

    @RequestMapping("selectUser")
    public String selectUser(){
        return user;
    }

    @RequestMapping("selectConfig")
    public String selectConfig(){
        return username + ","+age + "," + sex;
    }

    public String failCallback(){
        return "-1";
    }

    private void getMetaData(List<ServiceInstance> instanceList){
        for(ServiceInstance instance : instanceList){
            Map<String, String> map = instance.getMetadata();
            for(Map.Entry<String,String> entry : map.entrySet()){
                String key = entry.getKey();
                String value = entry.getValue();
                System.out.println("获取到服务提供方注册的元数据-----key: " + key +" ,value: "+ value);
            }
        }
    }
}
